/*
 * Copyright 2013 Philip Luyckx
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.pluyckx.batteryprogress.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;

import be.pluyckx.batteryprogress.application.Constants;
import be.pluyckx.batteryprogress.service.BatteryProgressService;

/**
 * Created by Philip Luyckx on 7/30/13.
 */
public class BatteryStateReceiver extends BroadcastReceiver {
  private static final String TAG = "BatteryStateReceiver";

  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent != null && intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
      updateService(context, intent);
    }
  }

  public static void updateService(Context context, Intent intent) {
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    boolean discharging = (intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0) == BatteryManager.BATTERY_STATUS_DISCHARGING);
    boolean charging = (intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0) == BatteryManager.BATTERY_STATUS_CHARGING);
    // boolean charging = false; // force false for debugging

    if (Constants.DEBUG) {
      Log.d(TAG, "Status: " + intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0));
    }

    context.startService(BatteryProgressService.createIntentBatteryLevel(context, level, scale, charging, discharging));
  }
}
